package com.dcxm.stu.controller;

import com.dcxm.stu.bean.HomeWork;
import com.dcxm.stu.api.HomeWorkInfo;
import com.dcxm.stu.service.impl.HomeWorkServiceI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/homework")
public class HomeWorkController {

    private HomeWork homeWork = new HomeWork(null, null, null, null, null);

    private final HomeWorkServiceI serviceI;

    @Autowired
    public HomeWorkController(HomeWorkServiceI serviceI) {
        this.serviceI = serviceI;
    }

    /**
     * @param request 请求参数
     * @return homework的json
     */
    @RequestMapping("/add")
    public HomeWorkInfo addHomeWork(@RequestParam("files") CommonsMultipartFile[] files, HttpServletRequest request) {
        homeWork.setName(request.getParameter("name"));
        homeWork.setContent(request.getParameter("content"));
        String path = request.getSession().getServletContext().getRealPath("/upload/");
        return serviceI.insertHomeWork(homeWork, files, path);
    }

    /**
     * 作业删除
     *
     * @param request 请求参数
     * @return homework 的 json
     */
    @RequestMapping("/delete")
    public HomeWorkInfo deleteHomeWork(HttpServletRequest request) {
        return serviceI.deleteHomeWork(request.getParameter("id"));
    }

    @RequestMapping("/list")
    public HomeWorkInfo homeWorkList() {
        return serviceI.listHomeWork();
    }

    // 用 , 隔开
    @RequestMapping("/select_id")
    public HomeWorkInfo homeWorkId(HttpServletRequest request) {
        String[] ids = request.getParameter("ids").split(",");
        return serviceI.listSelectHomeWorkById(ids);
    }

    @RequestMapping("/select_type")
    public HomeWorkInfo homeWorkType(HttpServletRequest request) {
        return serviceI.listSelectHomeWorkByType(request.getParameter("type"));
    }

    /**
     * 根据 id 来更新作业 <b>未测试<b/>
     *
     * @param request 前端请求
     * @return homeWorkInfo
     */
    @RequestMapping("/update_homework")
    public HomeWorkInfo updateHomeWork(HttpServletRequest request) {
        homeWork.setId(Long.valueOf(request.getParameter("id")));
        homeWork.setName(request.getParameter("name"));
        homeWork.setContent(request.getParameter("content"));
        homeWork.setType(request.getParameter("type"));
        return serviceI.updateHomeWork(homeWork);
    }
}
